package com.tx.admin.core.anno.aop;

import java.lang.reflect.Method;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import com.tx.admin.core.anno.RequestMax;
import com.tx.admin.core.exception.SuperException;
import com.tx.admin.util.common.AopUtil;
import com.tx.admin.util.common.RedisUtil;
import com.tx.admin.util.common.StringUtil;
import com.tx.admin.util.web.SessionUtil;

import lombok.extern.slf4j.Slf4j;

@Component
@Aspect
@Slf4j
public class RequestMaxAop {

	private static final String key="RequestMaxAop";
	
	@Pointcut("@annotation(com.tx.admin.core.anno.RequestMax)")
	public void aop() {
			
	}
	
	
	
	@Around("aop()")  
	public Object doAroundAdvice(ProceedingJoinPoint pjp) throws Throwable{  
	   	log.info("请求切面");
		String id = SessionUtil.getId();
		MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method method = ms.getMethod();
        RequestMax requestMax = AnnotationUtils.findAnnotation(method, RequestMax.class); 
		String key = id + method.hashCode();
	    long max = RedisUtil.incr(key, requestMax.locktime());  
	    if(max >= requestMax.value()) {
	        long locktime = RedisUtil.ttl(key);
		    Map params = AopUtil.getParams(pjp);
		    params.put("locktime", locktime);
		    String errorMsg ="函数"+id+":"+ StringUtil.render(requestMax.errorMsg(), params);
		    throw new SuperException(errorMsg);
	    }
	    Object val = pjp.proceed();
	    return val;
	}
	  
}
